//
//  LJStatusPictureView.swift
//  LJWeibo
//
//  Created by Raymond on 15/12/22.
//  Copyright © 2015年 liu. All rights reserved.
//

import UIKit
import SDWebImage

// MARK: - 通知名称
/// cell被点击的通知名称
let LJStatusPictureViewCellDidSelectNotication = "LJStatusPictureViewCellDidSelectNotication"

/// 被点击的cell对应indexpath的KEY
let LJStatusPictureViewCellDidSelectIndexPathKey = "LJStatusPictureViewCellDidSelectIndexPathKey"

/// 被点击的cell对应大图URL的KEY
let LJStatusPictureViewCellDidSelectURLKey = "LJStatusPictureViewCellDidSelectURLKey"

class LJStatusPictureView: UICollectionView {

    /// MARK: - 属性
    
    /// 布局对象
    private var layout = UICollectionViewFlowLayout()
    /// 回收标示
    private let ReuseIdentifier = "LJStatusPictureCell"
    /// 模型对象
    var status: LJStatus? {
        didSet {
            // 赋值时刷新数据
            self.reloadData()
        }
    }
    
    /// 计算View大小的方法
    func calcViewSize() -> CGSize {
        let itemSize = CGSize(width: 90, height: 90)
        // 间距
        let margin: CGFloat = 10
        // 设置layout
        layout.itemSize = itemSize
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        // 图片数量
        let count = status?.pictureURLs?.count ?? 0
        
        if count == 0 {
            return CGSizeZero
        }
        
        if count == 1 {
            var size = CGSize(width: 150, height: 120)
            let url = status!.pictureURLs!.first!
            // 获取缓存图片
            let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(url.absoluteString)
            size = image.size
            // 如果图片过宽或过窄要改变
            if size.width < 40 {
                size.width = 40
            }else if size.width > UIScreen.mainScreen().bounds.width * 0.5 {
                size.width = UIScreen.mainScreen().bounds.width * 0.5
            }
            layout.itemSize = size
            return size
        }
        
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = margin
        
        if count == 4 {
            let width = 2 * itemSize.width + margin
            return CGSize(width: width, height: width)
        }
        // 列数
        let col = 3
        // 宽
        let width = itemSize.width * CGFloat(col) + CGFloat(col - 1) * margin
        // 行数
        let row = (count + col - 1) / col
        // 高
        let height = itemSize.height * CGFloat(row) + CGFloat(row - 1) * margin
        return CGSize(width: width, height: height)
        
    }
    
    /// MARK: - 构造方法
    
    init() {
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        // 设置背景色
        backgroundColor = UIColor.clearColor()
        // 注册cell
        registerClass(LJStatusPictureViewCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
        // 指定数据代理
        self.dataSource = self
        self.delegate = self
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
/// MARK: - 分类
extension LJStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    /// MARK: - collectionView 数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.pictureURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! LJStatusPictureViewCell
        // 取出模型
        let imageURL = self.status?.pictureURLs?[indexPath.item]
        
        cell.imageURL = imageURL
        return cell
    }
    /// MARK: - collectionView 代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 打印对应得小图和大图地址
//        let largeURL = status!.largePictureURLS![indexPath.item] 
//        print(largeURL.absoluteString)
        
        // 发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(LJStatusPictureViewCellDidSelectNotication, object: self, userInfo: [LJStatusPictureViewCellDidSelectIndexPathKey: indexPath, LJStatusPictureViewCellDidSelectURLKey: status!.largePictureURLS!])
    }
}
/// MARK: - 自定义Cell
class LJStatusPictureViewCell: UICollectionViewCell {
    // 属性
    /// 图片URL
    var imageURL: NSURL? {
        didSet {
            let isGif = imageURL!.absoluteString.lowercaseString.hasSuffix("gif")
            gifImageView.hidden = !isGif
            
            imageView.sd_setImageWithURL(imageURL)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 准备UI
    func prepareUI() {
        // 添加控件
        contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)
        // 设置约束
        imageView.ff_Fill(contentView)
        gifImageView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: contentView, size: nil)
    }
    // MARK: - 懒加载
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView(image: nil)
        
        // 设置图片填充模式
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        //剪切图片
        imageView.clipsToBounds = true
        return imageView
        
        
    }()
    // gif标志
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}